import random

from app import db
from app.models.str_util_models import StrGenerationHistory
from app.config import Config



class StringGenerator:
    """字符串生成器服务类"""

    # 字符类型映射
    CHAR_TYPE_MAP = {
        'digits': Config.DEFAULT_DIGITS,
        'letters': Config.DEFAULT_LETTERS,
        'digits_letters': Config.DEFAULT_DIGITS + Config.DEFAULT_LETTERS,
        'symbols': Config.DEFAULT_SYMBOLS,
        'digits_letters_symbols': Config.DEFAULT_DIGITS + Config.DEFAULT_LETTERS + Config.DEFAULT_SYMBOLS,
        'chinese': Config.DEFAULT_CHINESE,
        'custom': ''  # 自定义字符集，需要用户提供
    }

    @classmethod
    def generate_string(cls, length, char_type, prefix='', suffix='', custom_chars=''):
        """
        生成指定类型的字符串

        Args:
            length (int): 字符串长度
            char_type (str): 字符类型
            prefix (str): 前缀
            suffix (str): 后缀
            custom_chars (str): 自定义字符集

        Returns:
            str: 生成的字符串
        """
        # 验证参数
        if not isinstance(length, int) or length <= 0:
            raise ValueError("长度必须是正整数")

        if char_type not in cls.CHAR_TYPE_MAP:
            raise ValueError(f"不支持的字符类型: {char_type}")

        if char_type == 'custom' and not custom_chars:
            raise ValueError("自定义字符类型需要提供custom_chars参数")

        # 获取字符集
        if char_type == 'custom':
            charset = custom_chars
        else:
            charset = cls.CHAR_TYPE_MAP[char_type]

        if not charset:
            raise ValueError("字符集不能为空")

        # 计算实际需要生成的随机部分长度
        random_length = max(0, length - len(prefix) - len(suffix))

        # 生成随机部分
        if random_length > 0:
            random_part = ''.join(random.choice(charset) for _ in range(random_length))
        else:
            random_part = ''

        # 组合前缀、随机部分和后缀
        result = prefix + random_part + suffix

        # 如果结果长度超过指定长度，截断
        if len(result) > length:
            result = result[:length]

        return result

    @classmethod
    def generate_and_save(cls, length, char_type, prefix='', suffix='', custom_chars=''):
        """生成字符串并保存到数据库"""
        generated_string = cls.generate_string(length, char_type, prefix, suffix, custom_chars)

        # 保存到数据库
        history = StrGenerationHistory(
            length=length,
            char_type=char_type,
            prefix=prefix,
            suffix=suffix,
            custom_chars=custom_chars,
            generated_string=generated_string
        )

        db.session.add(history)
        db.session.commit()

        return generated_string, history.id

    @classmethod
    def get_history(cls, limit=10, offset=0):
        """获取生成历史"""
        return StrGenerationHistory.query.order_by(
            StrGenerationHistory.created_at.desc()
        ).offset(offset).limit(limit).all()

    @classmethod
    def get_history_by_id(cls, history_id):
        """根据ID获取历史记录"""
        return StrGenerationHistory.query.get(history_id)

    @classmethod
    def clear_history(cls):
        """清空历史记录"""
        StrGenerationHistory.query.delete()
        db.session.commit()